from django.shortcuts import render
# Create your views here.
from django.shortcuts import render
from django.template import loader
from django.utils import timezone
from django.http import Http404
from django.views import generic
from django.shortcuts import get_object_or_404
import xlwt
import datetime
from django.http import HttpResponse, HttpResponseRedirect
from .models import Competitor
# Create your views here.
def apply(request):
    return render(request, 'apply/login.html')

def get_list(request):
    response = HttpResponse(content_type='application/vnd.ms-excel')
    response['Content-Disposition'] = 'attachment;filename=all.xls'
    wb = xlwt.Workbook(encoding='utf-8')
    stradd = u'所有人报名详情'
    sheet = wb.add_sheet(stradd)
    # 1st line
    sheet.col(0).width = 256 * 20
    sheet.col(1).width = 256 * 20
    sheet.col(2).width = 256 * 20
    sheet.col(3).width = 256 * 20
    sheet.col(4).width = 256 * 20

    sheet.write(0, 0, 'ID')
    sheet.write(0, 1, '姓名')
    sheet.write(0, 2, '专业或班级')
    sheet.write(0, 3, '报名时间')
    row = 1
    for obj in Competitor.objects.all():
        sheet.write(row, 0, obj.Competitor_ID)
        sheet.write(row, 1, obj.Competitor_name)
        sheet.write(row, 2, obj.Competitor_zhuanye)
        sheet.write(row, 3, obj.Competitor_day.strftime('%Y%m%d%H%M') )
        row = row + 1

    wb.save(response)
    return response


def get_in_apply(request):

    try:
        id = request.POST['id']
        name=request.POST['name']
        zhuanye=request.POST['zhuanye']
        if(id ==''or name==''or zhuanye==''):
            return render(request, 'apply/error.html', {'error_msg': '报名失败！！！请输入正确的信息', 'id': None})
        nowtime = datetime.datetime.now()

    except:

        return render(request, 'apply/error.html', {'error_msg': '报名失败！！！请重试', 'id': None})
    else:
        print(id)
        print(name)
        print(zhuanye)
        print(nowtime)
        if Competitor.objects.filter(Competitor_ID=id).first() != None:
            return render(request, 'apply/error.html', {'error_msg': '您已报名，如若有问题请联系管理员QQ407157175', 'id': None})
        else:

            dic = {'Competitor_name':name,'Competitor_ID':id,'Competitor_zhuanye':zhuanye,'Competitor_day':nowtime}
            Competitor.objects.create(**dic)
    return render(request, 'apply/error.html', {'error_msg': '您已成功报名', 'id': None})

